//
//  GradientChartBar.swift
//  PBFinanceBusiness
//
//  Created by xinph on 2020/7/23.
//

import UIKit
import CZBFoundation

// MARK: - life cycle
public class GradientChartBar: CZBView {
    
    /// 允许的偏移量
    var allowOffset: CGFloat = RealValue(28)
    /// title距离bar之间的距离
    var margin: CGFloat = RealValue(12)
    var colors = [UIColor.hex("#f9f3e6"), UIColor.hex("#f1e5cb")]
    var animation = false

    /// 0~1
    var scale: String = "0"
    
    lazy var gradientView: UIView = {
        var lazyView = UIView()
        return lazyView
    }()
    
    lazy var titleLabel: UILabel = {
        var lazyView = UILabel(font: DIN_Medium_Font(12), textColor: UIColor.hex("#DBB171"), alignment: .center)
        return lazyView
    }()
    
    convenience init(_ animation: Bool = false, scale: String, colors: [UIColor] = [UIColor.hex("#E1CCA1"), UIColor.hex("#F1E5CB")], title: String) {
        self.init()
        self.animation = animation
        self.scale = scale
        self.colors = colors
        titleLabel.text = title
    }
}

// MARK: - UI
extension GradientChartBar {
    public override func setupUI() {
        
        addSubview(titleLabel)
        addSubview(gradientView)
    }

    public override func layoutSubviews() {
        super.layoutSubviews()
        
        guard self.frame.height > 0 else { return }
        titleLabel.sizeToFit()
        let heightStr = Multiplying((self.frame.height-titleLabel.frame.height-margin-allowOffset), otherNumber: min(scale, b: 1)) ?? "0"
        let height = CGFloat(Double(heightStr)!)
        gradientView.frame = CGRect(x: 0, y: self.frame.height-height, width: self.frame.width, height: height)
        titleLabel.frame = CGRect(x: 0, y: gradientView.frame.origin.y-margin-titleLabel.frame.height, width: self.frame.width, height: titleLabel.frame.height)
        /// 更新渐变色
        updateGradient()
    }
    
    fileprivate func updateGradient() {
        guard colors.count >= 2 else {
            gradientView.backgroundColor = colors.first
            return
        }
        gradientView.addVerticalGradientLayer(colors.first!, rightColor: colors[1])
    }
    
    /// 获取最小值
    /// - Parameters:
    ///   - a: a description
    ///   - b: b description
    /// - Returns: 最小值
    fileprivate func min(_ a: Any, b: Any) -> Any {
        if CompareNumber(with: a, otherNumber: b) == .orderedAscending {
            return a
        }
        return b
    }
}

// MARK: - Action
extension GradientChartBar {
    
}

// MARK: - Delegate
extension GradientChartBar {
    
}

func DIN_Medium_Font(_ size: CGFloat) -> UIFont {
    return UIFont(name: "DIN-Medium", size: size) ?? .size(size)
}
